package com.hzit.pay.web.customer;

import com.hzit.pay.web.config.PayWebConfig;
import com.hzit.pay.web.config.RabbitMqConfig;
import com.hzit.pay.web.mapper.PayNoticeMapper;
import com.hzit.pay.web.model.PayNotice;
import com.hzit.payweb.api.resp.PayNotifyReq;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * 支付回调消费者
 */
@Component
public class PayNotifyCustomer {


    private static final Logger logger = LoggerFactory.getLogger(PayNotifyCustomer.class);

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PayWebConfig payWebConfig;

    @Autowired
    private PayNoticeMapper payNoticeMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     *
     * @param payNotifyReq
     * @param channel
     */
    @RabbitListener(queues = RabbitMqConfig.DEAD_LETTER_QUEUEA_NAME)
    public void recivePayDeadQueueMsg(PayNotifyReq payNotifyReq, Channel channel){
        logger.info("########支付回调消费者开始消费：{}#########",payNotifyReq);

        //订单，还款服务
        String result = restTemplate.postForObject(payWebConfig.getRepayNotifyUrl(),payNotifyReq,String.class);


        logger.info("########流水号为：{}收到业务系统的回调通知返回结果：{}#########",payNotifyReq.getPaySerialNo(),result);

        PayNotice payNotice = payNoticeMapper.selectByPaySerialNo(payNotifyReq.getPaySerialNo());

        if("success".equals(result)){
            payNoticeMapper.updateCount(payNotifyReq.getPaySerialNo(),"0");
            return;
        }

        if(payNotice.getNoticeCount() == 5){

            PayNotice record = new PayNotice();

            record.setUpdateTime(new Date());
            record.setStatus("-1");
            payNoticeMapper.updateByPrimaryKey(record);
            return;
        }

        // 设置这条消息的过期时间
        rabbitTemplate.convertAndSend(RabbitMqConfig.BUSINESS_EXCHANGE_NAME, "", payNotifyReq, message -> {
            MessageProperties messageProperties = message.getMessageProperties();

            //TODO
            String time = "300000";
            if(payNotice.getNoticeCount() == 1){
                 time = "300000";
            } else if(payNotice.getNoticeCount() == 2){
                time = "600000";
            }else if(payNotice.getNoticeCount() == 3){
                time = "1500000";
            }
            messageProperties.setExpiration(time); //时间配置
            return message;
        });
        channel.r
    }

}
